package com.fenghongzhang.day016;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class Main2Activity extends AppCompatActivity {
    private ListView lv;
    private Button pasue;
    private Button restart;
    private Button stop;
    private Button pre;
    private static final String TAG = "Main2Activity";
    private Button next;
    private Button modle;
    List<Music> music;
    private int index = 0;
    private SeekBar seekbar;

    private Timer timer;
    //播放模式的值
    private int playModle = 0;
    private MediaPlayer mediaPlayer;
    private List<Music> list;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            readData();
        }else{
            finish();
        }
    }

    private void readData() {
        Log.i(TAG, "readData: 222");
        //2,数据源
             music = MusicUtil.getMusic(this);
        //3,适配器
            MyAdapter myAdapter = new MyAdapter(music,this);
            lv.setAdapter(myAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        mediaPlayer = new MediaPlayer();

        seekbar = (SeekBar) findViewById(R.id.seekbar);

        lv = (ListView) findViewById(R.id.lv);
        pasue = (Button) findViewById(R.id.pasue);
        restart = (Button) findViewById(R.id.restart);
        stop = (Button) findViewById(R.id.stop);
        pre = (Button) findViewById(R.id.pre);
        next = (Button) findViewById(R.id.next);
        modle = (Button) findViewById(R.id.modle);


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ //
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
        }else{
            //2,数据源
            readData();
        }

        //点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                play(position);
            }
        });


        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    private void play(int position) {
        if(timer == null){
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    seekbar.setProgress(mediaPlayer.getCurrentPosition());
                }
            },0,1000);
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(list.get(position).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                    seekbar.setMax(mediaPlayer.getDuration());
                }
            });


            //播完完成的监听器
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //自动调用
                    switch (playModle){
                        case MusicUtil.RANDOM:
                            index = new Random().nextInt(list.size());
                            play(index);
                            break;
                        case MusicUtil.ORDER:
                            next();
                            break;
                        case MusicUtil.SINGE:
                            play(index);
                            break;

                    }
                }
            });

            //播放出错的监听器
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    return false;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pause(View view) {
        mediaPlayer.pause();
    }

    public void restart(View view) {
        mediaPlayer.start();
    }

    public void stop(View view) {
        mediaPlayer.stop();
    }

    //上一首
    public void pre(View view) {
        index--;
        if(index <= 0){
            index = 0;
        }
        play(index);
    }

    //下一首
    public void next(View view) {
        next();
    }

    private void next() {
        index++;
        if(index > list.size()-1){
            index = 0;
        }
        play(index);
    }

    //主要是修改下标.
    public void modle(View view) {
        final PopupWindow popupWindow = new PopupWindow();
        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);
        popupWindow.setContentView(inflate);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView order = inflate.findViewById(R.id.pop_order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Main2Activity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                playModle = MusicUtil.ORDER;
                popupWindow.dismiss();
            }
        });


        TextView random = inflate.findViewById(R.id.pop_random);
        random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModle = MusicUtil.RANDOM;
                Toast.makeText(Main2Activity.this, "随机播放", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        TextView singe = inflate.findViewById(R.id.pop_singe);
        singe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModle = MusicUtil.SINGE;
                Toast.makeText(Main2Activity.this, "单曲播放", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });


        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(modle,0,-300);
    }
}
